package com.ruoyi.door.utils;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSONObject;
import com.easy.query.api.proxy.client.EasyEntityQuery;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.door.domain.DoorTemplateLog;
import com.ruoyi.door.domain.DoorWxToken;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class WxTemplate {
    @Value("${weChat.mp.appId}")
    private String mpAppId;
    @Value("${weChat.mp.appSecret}")
    private String mpAppSecret;

    @Autowired
    private RedisCache redisCache;
    @Autowired
    private EasyEntityQuery easyEntityQuery;
    public static final String MESSAGE_SUBSCRIBE_SEND = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=ACCESSTOKEN";


    //人脸门禁缴费：https://charging-test.szhansel.com/#/pages/mine/payment/index
    //缴纳运维费：https://charging-test.szhansel.com/#/pages/mine/maintenance/index
    //购买门禁卡：https://charging-test.szhansel.com/#/pages/mine/accesscard/index
    public String gongdan(String orderNo, String openId,String createTime,String workName,String name, String address, String phone) {
        JSONObject data = new JSONObject();
        //账单类型
        JSONObject time6 = new JSONObject();
        time6.put("value", createTime);
        data.put("time6", time6);

        JSONObject thing8 = new JSONObject();
        thing8.put("value", StrUtil.sub(workName, 0, 19));
        data.put("thing8", thing8);

        JSONObject thing5 = new JSONObject();
        thing5.put("value", name);
        data.put("thing5", thing5);

        JSONObject thing16 = new JSONObject();
        thing16.put("value", address);
        data.put("thing16", thing16);

        JSONObject phone_number32 = new JSONObject();
        phone_number32.put("value", phone);
        data.put("phone_number32", phone_number32);
        return send(getAccessToken2(orderNo), openId, "BlvxW_Lx0Lb1ZdMeFFfJmwesVP5xF87UvloX-2fRx6g",
                "https://charging-test.szhansel.com/#/pages/workorder/todo", data, orderNo);
    }

    /**
     * @param openId
     * @param address      地址
     * @param phone        手机号
     * @param jiaofeixiang 缴费项
     * @param amount       缴费金额
     * @return
     */
    public String renLian(String orderNo, String openId, String address, String phone, String jiaofeixiang, String amount) {


        JSONObject data = new JSONObject();
        //账单类型
        JSONObject thing9 = new JSONObject();
        thing9.put("value", "人脸缴费");
        data.put("thing9", thing9);


        //地址
        JSONObject thing17 = new JSONObject();
        thing17.put("value", getAddress(address));
        data.put("thing17", thing17);

        JSONObject phone_number40 = new JSONObject();
        phone_number40.put("value", phone);
        data.put("phone_number40", phone_number40);

        JSONObject const26 = new JSONObject();
        const26.put("value", jiaofeixiang);
        data.put("const26", const26);

        //缴费金额
        JSONObject amount3 = new JSONObject();
        amount3.put("value", amount);
        data.put("amount3", amount3);


        return send(getAccessToken2(orderNo), openId, "XzPc-qsNw8jgNADT9Oj8Q0W3QENIQvHRwLeZHMliDtY",
                "https://charging-test.szhansel.com/#/pages/homeWorkbench/index", data, orderNo);
    }

    /**
     * 门禁卡
     *
     * @param openId
     * @param address 地址
     * @param phone   手机号
     * @param bishu   缴费笔数
     * @param amount  缴费金额
     * @return
     */
    public String menJinKa(String orderNo, String openId, String address, String phone, String bishu, String amount) {

        JSONObject data = new JSONObject();
        //账单类型
        JSONObject thing9 = new JSONObject();
        thing9.put("value", "门禁卡");
        data.put("thing9", thing9);


        //地址
        JSONObject thing17 = new JSONObject();
        thing17.put("value", getAddress(address));
        data.put("thing17", thing17);

        JSONObject phone_number40 = new JSONObject();
        phone_number40.put("value", phone);
        data.put("phone_number40", phone_number40);

        JSONObject character_string27 = new JSONObject();
        character_string27.put("value", bishu);
        data.put("character_string27", character_string27);

        //缴费金额
        JSONObject amount3 = new JSONObject();
        amount3.put("value", amount);
        data.put("amount3", amount3);


        return send(getAccessToken2(orderNo), openId, "XzPc-qsNw8jgNADT9Oj8Q6UhImiKYPXP-hplBwdJvG4",
                "https://charging-test.szhansel.com/#/pages/homeWorkbench/index", data, orderNo);
    }

    /**
     * 运维费
     * <p><a href="https://mp.weixin.qq.com/advanced/tmplmsg?action=new_tmpl_detail&pri_tmpl_id=XzPc-qsNw8jgNADT9Oj8Q2D0lBN6JQJnDHd7tiLkxmU&token=1175668781&lang=zh_CN">...</a></p>
     *
     * @param openId
     * @param mjbm    门禁编码
     * @param address 地址
     * @param amount  缴费金额
     * @return
     */
    public String yunWeiFei(String orderNo, String openId, String mjbm, String address, String phone, String amount) {

        JSONObject data = new JSONObject();
        //账单类型
        JSONObject thing9 = new JSONObject();
        thing9.put("value", "运维费");
        data.put("thing9", thing9);

        //门禁编号
        JSONObject character_string39 = new JSONObject();
        character_string39.put("value", mjbm);
        data.put("character_string39", character_string39);

        //地址
        JSONObject thing17 = new JSONObject();
        thing17.put("value", getAddress(address));
        data.put("thing17", thing17);

        JSONObject phone_number40 = new JSONObject();
        phone_number40.put("value", phone);
        data.put("phone_number40", phone_number40);

        //缴费金额
        JSONObject amount3 = new JSONObject();
        amount3.put("value", amount);
        data.put("amount3", amount3);


        return send(getAccessToken2(orderNo), openId, "XzPc-qsNw8jgNADT9Oj8Q2D0lBN6JQJnDHd7tiLkxmU",
                "https://charging-test.szhansel.com/#/pages/homeWorkbench/index", data, orderNo);
    }

    private String getAddress(String address) {
        String[] split = address.split("/");
        if (split.length >= 2) {
            // 只要后两段
            String lastTwo = split[split.length - 2] + split[split.length - 1];
            return StrUtil.sub(lastTwo, 0, 20);
        } else {
            return StrUtil.sub(address, 0, 20);
        }
    }

    /**
     * 不缓存
     * @param orderNo
     * @return
     */
    public String getAccessToken2(String orderNo) {
        JSONObject accessToken = CgiBin.getAccessToken(mpAppId, mpAppSecret);
        if (!accessToken.containsKey("errcode") && accessToken.containsKey("access_token")) {
            return accessToken.getString("access_token");
        }else{
            throw new ServiceException(accessToken.getString("errmsg"));
        }
    }

    /**
     * reids缓存
     * @param orderNo
     * @return
     */
    public String getAccessTokenRedis(String orderNo) {
        String wxAccessToken = redisCache.getCacheObject("wx_access_token");
        if (StrUtil.isEmpty(wxAccessToken)) {
            //如果缓存是空的，就重新获取
            JSONObject accessToken = CgiBin.getAccessToken(mpAppId, mpAppSecret);
            System.out.println(accessToken.toJSONString());
            if (!accessToken.containsKey("errcode") && accessToken.containsKey("access_token")) {
                redisCache.setCacheObject("wx_access_token", accessToken.getString("access_token"), 6000, TimeUnit.SECONDS);
                wxAccessToken = accessToken.getString("access_token");
            }else{
                throw new ServiceException(accessToken.getString("errmsg"));
            }
        }
        return wxAccessToken;
    }

    /**
     * db缓存
     * @param orderNo
     * @return
     */
    public String getAccessTokenDb(String orderNo) {
        DoorWxToken doorWxToken = easyEntityQuery.queryable(DoorWxToken.class).orderBy(d -> d.createTime().desc()).firstOrNull();
        if (ObjectUtil.isNull(doorWxToken) ||
                DateUtil.between(doorWxToken.getCreateTime(), DateUtil.date(), DateUnit.SECOND) > 6000) {
            //如果缓存是空的，就重新获取
            JSONObject accessToken = CgiBin.getAccessToken(mpAppId, mpAppSecret);

            if (!accessToken.containsKey("errcode") && accessToken.containsKey("access_token")) {
                String wxAccessToken = accessToken.getString("access_token");

                easyEntityQuery.insertable(new DoorWxToken()
                        .setWxToken(wxAccessToken).setCreateTime(DateUtils.getNowDate())).executeRows();
                return wxAccessToken;
            } else {
                //插入日志
                easyEntityQuery.insertable(new DoorTemplateLog()
                        .setOrderNo(orderNo)
                        .setRequestBody(accessToken.getString("errmsg"))
                        .setCreateTime(DateUtils.getNowDate())).executeRows();
                return "";
            }
        }
        return doorWxToken.getWxToken();
    }

    /**
     * 发送模板消息
     *
     * @param accessToken
     * @param openId
     * @param templateId
     * @param json
     * @return
     */
    public String send(String accessToken, String openId, String templateId, String url, JSONObject json, String orderNo) {
        /*
        JSONObject data = new JSONObject();
        JSONObject thing5 = new JSONObject();
        thing5.put("value", task.getNotificationContent()+"|"+task.getAlertId());
        data.put("thing8", thing5);

        JSONObject time4 = new JSONObject();
        time4.put("value", DateUtil.format(DateUtil.date(),"yyyy-MM-dd HH:mm:ss"));
        data.put("time6", time4);
        */
        if (StrUtil.isBlank(orderNo)){
            return "";
        }
        JSONObject body = new JSONObject();
        body.put("touser", openId);//接受人的openId
        body.put("template_id", templateId);//模版ID
        body.put("url", url); // 点击跳转链接
        body.put("data", json);//如餐
        String requestUrl = MESSAGE_SUBSCRIBE_SEND.replace("ACCESSTOKEN", accessToken);
        log.info("模板消息请求:{}", json.toJSONString());
        String post = HttpUtil.post(requestUrl, body.toString());
        log.info("模板消息返回值:{}", post);
        easyEntityQuery.insertable(new DoorTemplateLog()
                .setTemplateId(templateId)
                .setOrderNo(orderNo)
                .setRequestBody(json.toJSONString())
                .setResponseBody(post)
                .setCreateTime(DateUtils.getNowDate())).executeRows();
        return post;
    }
}
